package com.weishi.project.sport.movement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.enums.RedisConstants;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.config.ThreadPoolConfig;
import com.weishi.framework.redis.RedisCache;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.sport.movement.selection.MovementSelection;
import com.weishi.project.sport.movement.service.MovementService;
import com.weishi.project.sport.movement.thread.MovementRunnable;
import com.weishi.project.sport.movement.vo.AlignmentVO;
import com.weishi.project.sport.movement.vo.AverageAndMaxVO;
import com.weishi.project.sport.movement.vo.ReturnTrainingDayVO;
import com.weishi.project.sport.movement.vo.TrainingReportBean;
import com.weishi.project.sport.trainingdata.vo.TypeValueVO;
import com.weishi.project.sport.trainingdata.vo.WaterRankingVO;
import com.weishi.project.system.service.ISysDictDataService;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 运动员 运动模块 接口 实现类
 */
@Service
@Transactional
public class MovementServiceImpl implements MovementService {


    /**
     * 训练 周 计划接口
     */
    @Autowired
    private ITrainingWeekService trainingWeekService;

    /**
     * 训练 日 计划 接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    /**
     * 请假表 接口
     */
    @Autowired
    private ILeaveFormService leaveFormService;

    /**
     * 分组表 接口
     */
    @Autowired
    private ITrainingGroupService trainingGroupService;

    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    /**
     * 训练成绩 接口
     */
    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * redis 数据库
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    /**
     * 注入线程池
     */
    @Resource
    private ThreadPoolConfig threadPoolConfig;

    /**
     * 运动模块增删改操作
     */
    @Autowired
    private MovementRunnable movementRunnable;

    /**
     * 心率表 接口
     */
    @Autowired
    private IHeartRateService heartRateService;

    /**
     * 字典子表 数据接口
     */
    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 测功仪数据接口
     */
    @Autowired
    private IDynamometerService dynamometerService;

    /**
     * 运动员接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 测功仪成绩排名 接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    @Autowired
    private IShipSpeedRecordService shipSpeedRecordService;

    /**
     * 心率计次数据
     */
    @Autowired
    private IHeartRateCountService heartRateCountService;

    /**
     * 测功仪分段数据 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;

    /**
     * 赛后数据表Service接口
     */
    @Autowired
    private IRaceDataService raceDataService;

    @Autowired
    private IHeartRateRecordService heartRateRecordService;


    /**
     * 运动员端--根据当前时间--查询我的运动计划列表--根据开始时间排序
     */
    @Override
    public AjaxResult getSportsPlan(String day, Integer userId) {

        // 1，首先查询这个运动员今天是否在请假中
        if (!sportsmanService.getById(userId).getStatus().equals("0")) {
            return AjaxResult.success("该运动员正在请假中！");
        } else {
            // 2，根据当前日期查询 训练计划 列表
            return AjaxResult.success(trainingDayService
                    .list(Wrappers.<TrainingDay>lambdaQuery()
                            .eq(TrainingDay::getDay, day)
                            .orderByAsc(TrainingDay::getStartTime)));
        }
    }


    /**
     * 运动员端--查询运动计划详情
     */
    @Override
    public AjaxResult getSportsPlanDetails(Integer userId, String id) {
        Integer ids = Integer.parseInt(id);
        List<ReturnTrainingDayVO> returnTrainingDayVOTwo = trainingDayService.getSportsPlanDetailsTwo(ids, userId);


        if (returnTrainingDayVOTwo.size() > 0) {
            // 直接根据 id 查询然后返回数据
            returnTrainingDayVOTwo.forEach(p -> {
                // 判断公里数
                System.out.println();
                if (p.getTrainingMode() == 0) {
                    p.setTrainingModeName("公里数");
                } else {
                    p.setTrainingModeName("时间");
                }

                // 判断浆位
                if (p.getOarType() == null) {
                    p.setOarTypeName("");
                    System.out.println();
                } else if (p.getOarType() == 0) {
                    p.setOarTypeName("双桨");
                } else if (p.getOarType() == 1) {
                    System.out.println();
                    p.setOarTypeName("左桨");
                } else if (p.getOarType() == 2) {
                    p.setOarTypeName("右桨");
                }

                // 判断号位
                if (p.getPosition() == null) {
                    p.setPositionName("");
                    System.out.println();
                } else if (p.getPosition() == -1) {
                    p.setPositionName("舵手");
                } else {
                    p.setPositionName(p.getPosition().toString());
                }


                // 判断天气 查询字典天气值
                if (p.getWeather() != null) {
                    List<TypeValueVO> sysDictDataList = dictDataService.getTypeValue("weather");
                    sysDictDataList.forEach(pp -> {
                        System.out.println();
                        if (p.getWeather().equals(pp.getDictValue())) {
                            p.setWeather(pp.getDictLabel());
                        }
                    });
                }
                // 判断天气结束


                // 判断风速 查询字典风速值
                if (p.getWindSpeed() != null) {
                    List<TypeValueVO> windSpeed = dictDataService.getTypeValue("wind_speed");
                    windSpeed.forEach(pp -> {
                        System.out.println();
                        if (p.getWindSpeed().equals(pp.getDictValue())) {
                            p.setWindSpeed(pp.getDictLabel());
                        }
                    });
                }
                // 判断风速结束


                // 判断场地因素 查询字典场地因素值
                if (p.getSiteFactors() != null) {
                    List<TypeValueVO> siteFactors = dictDataService.getTypeValue("site_factors");
                    siteFactors.forEach(pp -> {
                        System.out.println();
                        if (p.getSiteFactors().equals(pp.getDictValue())) {
                            p.setSiteFactors(pp.getDictLabel());
                        }
                    });
                }
                // 判断场地因素结束

                // 查询分段成绩
                List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                        .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                .eq(DynamometerSubsection::getSportsmanId, p.getSportsmanId())
                                .eq(DynamometerSubsection::getTrainingDayId, p.getTrainingDayId())
                                .eq(DynamometerSubsection::getGroupId, p.getGroupId())
                                .orderByAsc(DynamometerSubsection::getSegmentNumber));

                // 平均心率
                Integer averageHeartRate = 0;
                //平均速度
                double averageSpeed = 0;
                // 平均浆频
                Integer propellerFrequency = 0;
                for (int i = 0; i < dynamometerSubsectionList.size(); i++) {
                    if (dynamometerSubsectionList.get(i).getHeartRate() > 0) {
                        averageHeartRate += dynamometerSubsectionList.get(i).getHeartRate();
                    }
                    if (dynamometerSubsectionList.get(i).getSpeed() > 0) {
                        averageSpeed += dynamometerSubsectionList.get(i).getSpeed();
                    }
                    propellerFrequency += Integer.parseInt(dynamometerSubsectionList.get(i).getPropellerFrequency());
                }

                if (dynamometerSubsectionList.size() > 0) {
                    // 计算平均心率 并且存入字段值
                    p.setAverageHeartRate(averageHeartRate / dynamometerSubsectionList.size());
                    // 计算平均速度 并且存入字段值
                    p.setAverageSpeed(averageSpeed / dynamometerSubsectionList.size());
                    // 计算平均浆频
                    Integer propellerFrequencys = propellerFrequency/dynamometerSubsectionList.size();
                    p.setPropellerFrequency(propellerFrequencys.toString());
                }

            });


            /**
             * 根据训练课 id 查询所有的组
             */
            List<TrainingGroup> trainingGroupList = trainingGroupService
                    .list(Wrappers.<TrainingGroup>lambdaQuery()
                            .eq(TrainingGroup::getTrainingDayId, id));
            for (int i = 0; i < trainingGroupList.size(); i++) {
                if (returnTrainingDayVOTwo.size() <= i) {
                    ReturnTrainingDayVO returnTrainingDayVO = new ReturnTrainingDayVO();
                    StringUtils.copyProperties(returnTrainingDayVOTwo.get(0), returnTrainingDayVO);
                    if (returnTrainingDayVO.getTrainingMode() == 0) {
                        returnTrainingDayVO.setTrainingModeName("公里数");
                    } else {
                        returnTrainingDayVO.setTrainingModeName("时间");
                    }
                    returnTrainingDayVO.setSportsmanId(null);
                    returnTrainingDayVO.setAchievement("");
                    returnTrainingDayVO.setRowingKilometers(0.0);
                    returnTrainingDayVO.setWatt("");
                    returnTrainingDayVO.setName("");
                    returnTrainingDayVO.setPower("");
                    returnTrainingDayVO.setSr(null);
                    returnTrainingDayVO.setPropellerFrequency("");
                    returnTrainingDayVO.setGroupId(trainingGroupList.get(i).getId());
                    returnTrainingDayVO.setGroupName(trainingGroupList.get(i).getGroupName());
                    returnTrainingDayVOTwo.add(returnTrainingDayVO);
                }
            }

            return AjaxResult.success(returnTrainingDayVOTwo);

        } else {
            List<ReturnTrainingDayVO> returnTrainingDayVOTwo2 = trainingDayService.getSportsPlanDetailsTwo(ids, null);
            if (returnTrainingDayVOTwo2.size() > 0) {
                returnTrainingDayVOTwo2.forEach(p -> {
                    if (p.getTrainingMode() == 0) {
                        p.setTrainingModeName("公里数");
                    } else {
                        p.setTrainingModeName("时间");
                    }
                    p.setSportsmanId(null);
                    p.setAchievement("");
                    p.setRowingKilometers(0.0);
                    p.setWatt("");
                    p.setName("");
                    p.setPower("");
                    p.setSr(null);
                    p.setPropellerFrequency("");
                });
            }
            return AjaxResult.success(returnTrainingDayVOTwo2);
        }

    }


    /**
     * 运动员端--查询运动--乳酸
     */
    @Override
    public AjaxResult getLacticAcid(Integer userId, String firstLevel, Integer trainingMode, Integer groupId, Integer trainingDayId) {
        return AjaxResult.success(raceDataService.list(Wrappers.<RaceData>lambdaQuery()
                .eq(RaceData::getSportsmanId, userId)
                .eq(RaceData::getTrainingDayId, trainingDayId)
                .orderByDesc(RaceData::getCtime)));
    }


    /**
     * 运动员端--查询运动--专项成绩信息
     */
    @Override
    public AjaxResult getWaterInformation(Integer userId, Integer id, Integer trainingMode, String firstLevel, Integer groupId) {
        /**
         * 判断水上陆上
         */
        if (firstLevel.equals("special_training_water")) {
            // 查询记次表
            List<HeartRateCount> heartRateCountList = heartRateCountService.selectHeartRateCountList(groupId, userId);

            /*List<HeartRateCount> heartRateCountList2 = new ArrayList<>();

            if(heartRateCountList.size() > 0){
                if(heartRateCountList.size() == 1){
                    System.out.println();
                    heartRateCountList2.add(heartRateCountList.get(0));
                    return AjaxResult.success(heartRateCountList2);
                }else{

                    // 总数据
                    int size = heartRateCountList.size();
                    // 起始数
                    int index = 0;
                    for (int i = 0; i<heartRateCountList.size(); i++){
                            if(index < size){
                                HeartRateCount heartRateCount = new HeartRateCount();
                                StringUtils.copyProperties(heartRateCountList.get(i) , heartRateCount);
                                if(index == 0){
                                    heartRateCountList2.add(heartRateCount);
                                }else{
                                    System.out.println();
                                    Double totalDistance = heartRateCountList.get(i).getTotalDistance();
                                    Double totalDistance2 = heartRateCountList.get(index-1).getTotalDistance();
                                    Double totalDistance3 = totalDistance - totalDistance2;
                                    heartRateCount.setTotalDistance(totalDistance3);

                                    Integer pointAchievement = StringUtils.turnSecond(heartRateCountList.get(i).getPointAchievement());
                                    Integer pointAchievement2 = StringUtils.turnSecond(heartRateCountList.get(index-1).getPointAchievement());
                                    Integer pointAchievement3 = pointAchievement - pointAchievement2;
                                    heartRateCount.setPointAchievement(StringUtils.millisecondRotationTime(pointAchievement3));
                                    heartRateCountList2.add(heartRateCount);
                                }
                                index++;
                            }

                    }
                    return AjaxResult.success(heartRateCountList2);
                }

            }*/

            return AjaxResult.success(heartRateCountList);
        } else {
            // 陆上查询
            // 查询这个人的所有分段
            List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                    .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                            .eq(DynamometerSubsection::getSportsmanId, userId)
                            .eq(DynamometerSubsection::getTrainingDayId, id)
                            .eq(DynamometerSubsection::getTrainingMode, trainingMode)
                            .eq(DynamometerSubsection::getGroupId, groupId)
                            .orderByAsc(DynamometerSubsection::getSegmentNumber));

            List<DynamometerSubsection> dynamometerSubsectionList2 = new ArrayList<>();
            if (dynamometerSubsectionList.size() > 0) {
                if (dynamometerSubsectionList.size() == 1) {
                    dynamometerSubsectionList2.add(dynamometerSubsectionList.get(0));
                    return AjaxResult.success(dynamometerSubsectionList2);
                } else {

                    // 总数据
                    int size = dynamometerSubsectionList.size();
                    // 起始数
                    int index = 0;
                    for (int i = 0; i < dynamometerSubsectionList.size(); i++) {
                        //  trainingMode =  0 减时间  1 减距离
                        if (dynamometerSubsectionList.get(i).getTrainingMode() == 0) {
                            if (index < size) {
                                DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                                StringUtils.copyProperties(dynamometerSubsectionList.get(i), dynamometerSubsection);
                                if (index == 0) {
                                    dynamometerSubsectionList2.add(dynamometerSubsection);
                                } else {
                                    System.out.println();
                                    Integer lengthTime = StringUtils.turnSecond(dynamometerSubsectionList.get(i).getLengthTime());
                                    Integer lengthTime2 = StringUtils.turnSecond(dynamometerSubsectionList.get(index - 1).getLengthTime());
                                    Integer lengthTime3 = lengthTime - lengthTime2;
                                    dynamometerSubsection.setLengthTime(StringUtils.millisecondRotationTime(lengthTime3));
                                    dynamometerSubsectionList2.add(dynamometerSubsection);
                                }
                                index++;
                            }

                        } else {

                            if (index < size) {
                                DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                                StringUtils.copyProperties(dynamometerSubsectionList.get(i), dynamometerSubsection);
                                if (index == 0) {
                                    System.out.println();
                                    System.out.println();
                                    dynamometerSubsectionList2.add(dynamometerSubsection);
                                } else {
                                    System.out.println();
                                    System.out.println();
                                    double mileage = dynamometerSubsectionList.get(i).getMileage();
                                    double mileage2 = dynamometerSubsectionList.get(index - 1).getMileage();
                                    double mileage3 = mileage - mileage2;
                                    dynamometerSubsection.setMileage(mileage3);
                                    dynamometerSubsectionList2.add(dynamometerSubsection);
                                }
                                index++;
                            }

                        }


                    }
                    return AjaxResult.success(dynamometerSubsectionList2);
                }

            }
            return AjaxResult.success();
        }
    }


    /**
     * 运动员端--查询运动--专项成绩信息--成绩对标
     */
    @Override
    public AjaxResult getWaterAlignment(Integer userId, Integer id, Integer trainingMode, String firstLevel, Integer groupId) {
        AlignmentVO alignmentVO = new AlignmentVO();

        // 查询本次成绩
        List<ReturnTrainingDayVO> returnTrainingDayVO = trainingDayService.getWaterInformation(userId, id, trainingMode, firstLevel, groupId);
        if (returnTrainingDayVO.size() > 0) {
            alignmentVO.setThisResult(returnTrainingDayVO.get(0).getAchievement());
        }

        // 查询运动员专项最好成绩
        alignmentVO.setPersonalBest(trainingDayService.getPersonalBest(userId, trainingMode, firstLevel));

        // 查询冠军成绩
        List<TrainingGroupChannel> list = trainingGroupChannelService.list(Wrappers.<TrainingGroupChannel>lambdaQuery().orderByDesc(TrainingGroupChannel::getAchievement));
        if (list.size() > 0) {
            alignmentVO.setChampionship(list.get(0).getAchievement());
        }
        return AjaxResult.success(alignmentVO);
    }


    /**
     * 运动员端--查询运动--专项成绩信息--船速及浆频
     */
    @Override
    public AjaxResult getWaterShipPulp(Integer userId, Integer id, Integer trainingMode, String firstLevel, Integer groupId) {
        return AjaxResult.success(trainingDayService.getWaterInformation(userId, id, trainingMode, firstLevel, groupId));
    }


    Logger logger = Logger.getLogger("HeartRate");

    /**
     * 运动员端--运动模块--新增心率
     */
    @Override
    public AjaxResult addHeartRate(Integer userId, HeartRate heartRate) {
        logger.info("heartRate:"+userId+" msg:"+ heartRate.toString());
        try {
            Integer channelId = redisCache.getCacheObject(RedisConstants.Heart_Rate_Meter_Prefix + userId);
            if (channelId != null) {
                heartRate.setSportsmanId(userId);
                heartRate.setChannelId(channelId);
                heartRate.setCtime(new Date());
                Integer countId = redisCache.getCacheObject(RedisConstants.Channel_count_Prefix + channelId);
                if (countId == null) {
                    countId = 1;
                }
                heartRate.setHeartRateCountId(countId);
                heartRateService.save(heartRate);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("系统异常！");
    }


    /**
     * 运动员端--运动模块--查询测功仪数据
     */
    @Override
    public AjaxResult getDynamometerList(Integer userId, Integer groupId, Integer trainingDayId) {
        List<Dynamometer> dynamometerList = dynamometerService.list(Wrappers.<Dynamometer>lambdaQuery().eq(Dynamometer::getSportsmanId, userId).eq(Dynamometer::getGroupId, groupId).eq(Dynamometer::getTrainingDayId, trainingDayId).orderByDesc(Dynamometer::getCtime));
        if (dynamometerList.size() > 0) {
            return AjaxResult.success(dynamometerList.get(0));
        } else {
            return AjaxResult.success();
        }
    }


    /**
     * 运动员端--教练点击开始按钮
     */
    @Override
    public AjaxResult start(JSONObject jsonObject) {
        //启动船速仪设备计时
        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelService.getById(Integer.parseInt(jsonObject.get("channelId").toString()));
        if (trainingGroupChannel.getShipSpeedId() != null) {
            //船速仪开始计时,有效期3个小时
            redisCache.setCacheObject(RedisConstants.Channel_ShipSpeed_Status_Prefix + trainingGroupChannel.getShipSpeedId(), trainingGroupChannel.getId(), 3, TimeUnit.HOURS);
        }

        //启动心率表的数据（水上）
        TrainingAchievement params = new TrainingAchievement();
        params.setChannelId(trainingGroupChannel.getId());
        List<TrainingAchievement> list = trainingAchievementService.selectTrainingAchievementList(params);
        if (StringUtils.isNotEmpty(trainingGroupChannel.getBoatType()) && list != null && list.size() > 0) {
            for (TrainingAchievement trainingAchievement : list) {
                //心率表开始计数,有效期3个小时
                redisCache.setCacheObject(RedisConstants.Heart_Rate_Meter_Prefix + trainingAchievement.getSportsmanId(), trainingGroupChannel.getId(), 3, TimeUnit.HOURS);
            }
        }
        return AjaxResult.success();
    }


    /**
     * 运动员端--教练点击结束按钮
     */
    @Override
    public AjaxResult end(JSONObject jsonObject) {
        //关闭船速仪设备计时
        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelService.getById(Integer.parseInt(jsonObject.get("channelId").toString()));
        if (trainingGroupChannel.getShipSpeedId() != null) {
            //船速仪结束计时
            redisCache.deleteObject(RedisConstants.Channel_ShipSpeed_Status_Prefix + trainingGroupChannel.getShipSpeedId());
            //核算成绩
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //防止最后一计次未入库
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    shipSpeedRecordService.addShipSpeedRecord(trainingGroupChannel.getShipSpeedId(), trainingGroupChannel.getId());
                }
            });
            thread.start();
        }

        //关闭心率表设备计数
        TrainingAchievement params = new TrainingAchievement();
        params.setChannelId(trainingGroupChannel.getId());
        List<TrainingAchievement> list = trainingAchievementService.selectTrainingAchievementList(params);
        if (StringUtils.isNotEmpty(trainingGroupChannel.getBoatType()) && list != null && list.size() > 0) {
            redisCache.deleteObject(RedisConstants.Channel_count_Prefix + trainingGroupChannel.getId());
            for (TrainingAchievement trainingAchievement : list) {
                //心率表开始计数,有效期3个小时
                redisCache.deleteObject(RedisConstants.Heart_Rate_Meter_Prefix + trainingAchievement.getSportsmanId());
            }

            //核算成绩
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    //防止最后一计次未入库
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    heartRateRecordService.addRecord(trainingGroupChannel.getId());
                }
            });
            thread1.start();
        }
        return AjaxResult.success();
    }


    /**
     * 运动员端--新增测功仪数据
     */
    @Override
    public AjaxResult addDynamometer(JSONObject trainingReportBean, Integer userId) {

        TrainingReportBean trainingDetails = JSONObject.toJavaObject(trainingReportBean, TrainingReportBean.class);//将建json对象转换为Person对象
        if (StringUtils.isNull(trainingDetails)) {
            return AjaxResult.error("数据不能为空！");
        }

        trainingDetails.setUserId(userId);
        redisTemplate.boundListOps("MovementServiceImpl_addDynamometer_trainingReportBean").leftPush(trainingDetails);
        MovementSelection.setValue("MovementServiceImpl_addDynamometer");
        threadPoolConfig.threadPoolTaskExecutor().execute(movementRunnable);

        return AjaxResult.success();
    }


    /**
     * 运动员端--根据训练日 id  用户 userId 查询数据
     */
    @Override
    public AjaxResult getTrainingDayById(Integer id, Integer userId) {
        return AjaxResult.success(dynamometerService.list(Wrappers.<Dynamometer>lambdaQuery().eq(Dynamometer::getTrainingDayId, id).eq(Dynamometer::getSportsmanId, userId).orderByDesc(Dynamometer::getCtime)));
    }


    /**
     * 运动员端--根据主键删除测功仪数据
     */
    @Override
    public AjaxResult deleteDynamometerById(Integer id) {
        dynamometerService.removeById(id);
        return AjaxResult.success();
    }


    /**
     * 运动员端--根据主键 修改 测功仪数据
     */
    @Override
    public AjaxResult updateDynamometerById(Dynamometer dynamometer) {
        dynamometerService.updateById(dynamometer);
        return AjaxResult.success();
    }


    /**
     * 运动员端--测功仪--查询心率
     */
    @Override
    public AjaxResult getDynamometerHeartRate(Integer userId, Integer trainingDayId, Integer trainingMode, Integer groupId) {
        return AjaxResult.success(dynamometerService.list(Wrappers.<Dynamometer>lambdaQuery().eq(Dynamometer::getSportsmanId, userId).eq(Dynamometer::getTrainingDayId, trainingDayId).eq(Dynamometer::getTrainingMode, trainingMode).eq(Dynamometer::getGroupId, groupId).orderByAsc(Dynamometer::getCtime)));
    }


    /**
     * 运动员端--心率表--查询心率
     */
    @Override
    public AjaxResult getHeartRateList(Integer userId, Integer trainingDayId, Integer groupId) {
        return AjaxResult.success(heartRateService.list(Wrappers.<HeartRate>lambdaQuery().eq(HeartRate::getSportsmanId, userId).eq(HeartRate::getTrainingDayId, trainingDayId).eq(HeartRate::getGroupId, groupId).orderByAsc(HeartRate::getCtime)));
    }


    /**
     * 运动员端--计算平均心率，最大心率
     */
    @Override
    public AjaxResult getAverageAndMax(Integer userId, Integer trainingDayId, Integer trainingMode, Integer groupId, String firstLevel) {
        AverageAndMaxVO averageAndMaxVO = new AverageAndMaxVO();

        /**
         * 判断水上，还是陆上
         * 陆上 land_specific_training_dynamometer
         * 水上 special_training_water
         */
        if (firstLevel.equals("land_specific_training_dynamometer")) {
            // 陆上
            List<Dynamometer> dynamometerList = dynamometerService.list(Wrappers.<Dynamometer>lambdaQuery().eq(Dynamometer::getSportsmanId, userId).eq(Dynamometer::getTrainingDayId, trainingDayId).eq(Dynamometer::getTrainingMode, trainingMode).eq(Dynamometer::getGroupId, groupId).orderByDesc(Dynamometer::getHeartRate));
            if (dynamometerList.size() > 0) {
                // 测功仪最大心率
                averageAndMaxVO.setMaxHeartRate(dynamometerList.get(0).getHeartRate());
            }
            // 测功仪平均心率
            averageAndMaxVO.setAverageHeartRate(dynamometerService.getAverageHeartRate(userId, trainingDayId, trainingMode, groupId));
            // 陆上结束

        } else {
            // 水上
            List<HeartRate> heartRateList = heartRateService.list(Wrappers.<HeartRate>lambdaQuery().eq(HeartRate::getSportsmanId, userId).eq(HeartRate::getTrainingDayId, trainingDayId).eq(HeartRate::getGroupId, groupId).orderByDesc(HeartRate::getHr));
            if (heartRateList.size() > 0) {
                // 心率表最大心率
                averageAndMaxVO.setMaxHeartRate(heartRateList.get(0).getHr());
            }
            // 心率表平均心率
            averageAndMaxVO.setAverageHeartRate(heartRateService.getAverageHeartRate(userId, trainingDayId, groupId));
            // 水上结束
        }

        return AjaxResult.success(averageAndMaxVO);
    }


    /**
     * 运动员 -- 今日专项成绩排名
     */
    @Override
    public AjaxResult getThisDayRanking(Integer groupId, String boatType, Integer trainingDayId, Integer sex, Integer trainingMode, Integer kilometers, Double realClassHour, String firstLevel) {
        Integer ranking = 0;
        List<WaterRankingVO> waterRankingVOList = new ArrayList<>();
        List<WaterRankingVO> waterRankingVOListTwo = trainingAchievementService.getThisDayRankingVO(groupId, boatType, trainingDayId, sex, trainingMode, kilometers, realClassHour, firstLevel);
        // 获取所有人的名称
        List<String> nameList = new ArrayList<>();
        for (int i = 0; i < waterRankingVOListTwo.size(); i++) {
            WaterRankingVO waterRankingVO = new WaterRankingVO();
            StringUtils.copyProperties(waterRankingVOListTwo.get(i), waterRankingVO);
            waterRankingVO.setRanking(ranking += 1);
            waterRankingVOList.add(waterRankingVO);
            nameList.add(waterRankingVOListTwo.get(i).getName());
        }

        // 删除重复的 list
        List<String> newList = new ArrayList<>();
        for (String cd : nameList) {
            if (!newList.contains(cd)) {
                newList.add(cd);
            }
        }

        List<WaterRankingVO> waterRankingVOListTwo2 = new ArrayList<>();
        for (int i = 0; i < newList.size(); i++) {
            // 根据 运动员名称查询排名
            WaterRankingVO waterRankingVO = new WaterRankingVO();
            StringUtils.copyProperties(trainingAchievementService.getThisDayRankingVOSS(firstLevel, newList.get(i), trainingMode, kilometers, sex).get(0), waterRankingVO);
            waterRankingVO.setRanking(i + 1);
            waterRankingVOListTwo2.add(waterRankingVO);
        }

        return AjaxResult.success(waterRankingVOListTwo2);
    }


    /**
     * 运动员 -- 测功仪存储分段成绩
     */
    @Override
    public AjaxResult addDynamometerSubsection(Integer userId, DynamometerSubsection dynamometerSubsection) {
        dynamometerSubsection.setSportsmanId(userId);
        dynamometerSubsection.setCtime(new Date());
        if (dynamometerSubsection.getSpeed() > 0.0) {
            // 计算四舍五入
            double d = dynamometerSubsection.getSpeed();
            d = Math.round(d * 100) / 100.0;
            dynamometerSubsection.setSpeed(d);
        }
        dynamometerSubsectionService.save(dynamometerSubsection);

        /*// 根据 TrainingMode 判断时间还是公里数 0 是公里数 1 是时间
        if (dynamometerSubsection.getTrainingMode() == 0) {
            // 追加到航道表中的分段成绩，并且以空格隔开
            // 通过用户查询出航道 id ,再通过航道 id 查询分段成绩 并且追加进去
            List<TrainingAchievement> trainingAchievementList = trainingAchievementService
                    .list(Wrappers.<TrainingAchievement>lambdaQuery()
                            .eq(TrainingAchievement::getSportsmanId, userId));

            if (trainingAchievementList.size() > 0) {
                // 根据航道 id 查询成绩
                TrainingGroupChannel channel = trainingGroupChannelService
                        .getById(trainingAchievementList.get(0).getChannelId());
                // 分段成绩
                String segmentedTiming = channel.getSegmentedTiming() + " " + dynamometerSubsection.getLengthTime();
                TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
                trainingGroupChannel.setSegmentedTiming(segmentedTiming);
                trainingGroupChannel.setId(channel.getId());
                trainingGroupChannelService.updateById(trainingGroupChannel);
            }
        } else {
            // 追加到航道表中的分段成绩，并且以空格隔开
            // 通过用户查询出航道 id ,再通过航道 id 查询分段成绩 并且追加进去
            List<TrainingAchievement> trainingAchievementList = trainingAchievementService
                    .list(Wrappers.<TrainingAchievement>lambdaQuery()
                            .eq(TrainingAchievement::getSportsmanId, userId));

            if (trainingAchievementList.size() > 0) {
                // 根据航道 id 查询成绩
                TrainingGroupChannel channel = trainingGroupChannelService
                        .getById(trainingAchievementList.get(0).getChannelId());
                // 分段成绩
                System.out.println();
                String segmentedTiming = channel.getSegmentedTiming() + " " + dynamometerSubsection.getMileage();
                TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
                trainingGroupChannel.setSegmentedTiming(segmentedTiming);
                trainingGroupChannel.setId(channel.getId());
                trainingGroupChannelService.updateById(trainingGroupChannel);
            }
        }*/


        return AjaxResult.success();
    }


}
